package com.hnyc.service.impl;

import com.hnyc.domain.CandConstants;
import com.hnyc.domain.CandRole;
import com.hnyc.domain.RoleCountUser;
import com.hnyc.exception.ServiceException;
import com.hnyc.mapper.CandRoleMapper;
import com.hnyc.mapper.CandUserRoleMapper;
import com.hnyc.service.ICandRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: XieYingHao
 * @date: 2023/7/1 11:06
 */
@Service
public class CandRoleServiceImpl implements ICandRoleService {

    @Resource
    private CandRoleMapper candRoleMapper;

    @Resource
    private CandUserRoleMapper candUserRoleMapper;

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(CandRole role) {
        Long userId = Objects.isNull(role.getId()) ? -1L : role.getId();
        CandRole info = candRoleMapper.checkRoleNameUnique(role.getRoleName());
        if (!Objects.isNull(info) && info.getId().longValue() != userId.longValue()) {
            return CandConstants.NOT_UNIQUE;
        }
        return CandConstants.UNIQUE;
    }

    /**
     * 新增角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRole(CandRole role) {
        // 新增用户信息
        return candRoleMapper.insertRole(role);
    }

    /**
     * 修改角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRole(CandRole role) {
        return candRoleMapper.updateRole(role);
    }

    /**
     * 根据条件查询角色列表
     *
     * @param role 角色信息
     * @return 角色信息集合信息
     */
    @Override
    public List<RoleCountUser> selectRoleList(CandRole role) {
        List<CandRole> candRoles = candRoleMapper.selectRoleList(role);
        List<RoleCountUser> results = new ArrayList<>();
        for (CandRole candRole : candRoles) {
            int count = candUserRoleMapper.countUserRoleByRoleId(candRole.getId());
            results.add(new RoleCountUser(count,candRole.getRoleName()));
        }
        return results;
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public CandRole selectRoleById(Long roleId)
    {
        return candRoleMapper.selectRoleById(roleId);
    }


    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int deleteRoleById(Long roleId) {
        CandRole role = selectRoleById(roleId);
        if (candUserRoleMapper.countUserRoleByRoleId(roleId) > 0)
        {
            throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
        }
        return candRoleMapper.deleteRoleById(roleId);
    }

}
